package aspect_log;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.management.ObjectName;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by jack on 18/6/2.
 */
public class SyslogAspect {
    public static final int CODE_SUCCESS = 0;
    private Logger logger = LoggerFactory.getLogger(SyslogAspect.class);

    /**
     * 定义切点名为 controllerAspect,方法需要为空，只是表示了切点和切面的关系   这个方法还没有参数
     */
    @Pointcut("@annotation(aspect_log.SaveSysLog)")
    public void controllerAspect(){}

    @AfterReturning(pointcut = "controllerAspect()", returning = "res")
    public void doAfter(JoinPoint jointPoint, Object res) throws Exception{
        logger.debug("-------------AfterReturning 开始---------------");
        if( null == res ){
            return ;
        }
        Map<String, Object> map = Obj2Map(res);
        int code = (Integer) map.get("code");
        if(code == CODE_SUCCESS){
            return ;
        }
        String message = (String) map.get("message");

        //类名
        String targetName = jointPoint.getTarget().getClass().getName();
        //得到方法名
        String methodName = jointPoint.getSignature().getName();
        MethodSignature ms = (MethodSignature) jointPoint.getSignature();

        //参数 key
        String[] parameterNames = ms.getParameterNames();
        Object[] arguments = jointPoint.getArgs();
        Method method = ms.getMethod();

        SaveSysLog logParam = method.getAnnotation(SaveSysLog.class);


//        //拼参数
//        PartnerSystemLog sysLog = new PartnerSystemLog();
//        //获取用户
//        if(logParam.type() == InterfaceTypeConst.InterfaceType.APP){
//            sysLog.setUserId(getAppUserId());
//        }else{
//            sysLog.setUserId(getMgrUserId());
//        }
//        sysLog.setSend(logParam.send());
//        sysLog.setUrl(logParam.url());
//        sysLog.setType(logParam.type());
//        //入参字符串
//        StringBuffer jsonParamSb = new StringBuffer();
//        for(int i = 0;i < parameterNames.length;i++){
//            jsonParamSb.append(parameterNames[i]).append("=").append(JSONObject.toJSONString(arguments[i]));
//            if(i != (parameterNames.length - 1)){
//                jsonParamSb.append("&");
//            }
//        }
//        //截取返回json
//        if(jsonParamSb.toString().length() <= 1000){
//            sysLog.setJsonParam(jsonParamSb.toString());
//        }else{
//            sysLog.setJsonParam(jsonParamSb.toString().substring(0, 1000));
//        }
//        //出参
//        sysLog.setJsonResult(JSONObject.toJSONString(res));
//        StringBuffer remarkSb = new StringBuffer();
//        remarkSb.append(targetName).append(".").append(methodName).append("报错信息：").append(message);
//        //截取remark
//        if(remarkSb.toString().length() <= 1000){
//            sysLog.setRemark(remarkSb.toString());
//        }else{
//            sysLog.setRemark(remarkSb.toString().substring(0, 1000));
//        }
//        sysLog.setCreateTime(new Date());
//        sysLog.setUpdateTime(new Date());
//        handleLog(sysLog);


        logger.debug("---------------AfterReturning结束--------------");

    }

    /**
     * 通过反射来获取到Object中的所有的属性与值的对应关系，放置到map中存储
     */
    public Map<String, Object> Obj2Map(Object obj) throws Exception{
        Map<String, Object> map = new HashMap<String, Object>();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields){
            field.setAccessible(true);
            map.put(field.getName(), field.get(obj));
        }
        return map;
    }


}
